package com.filter;

import com.bean.vo.admin.Result;
import com.google.gson.Gson;
import com.utils.GsonUtils;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        Gson gson = GsonUtils.getGson();
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletRequest.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        httpServletResponse.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");

        if(!"OPTIONS".equals(httpServletRequest.getMethod())){
            if(auth(httpServletRequest)){
                //true  需要验证权限
                HttpSession session = httpServletRequest.getSession();
                System.out.println("filter:" + session + ":" + httpServletRequest.getRequestURI() + ":" + httpServletRequest.getMethod());
                System.out.println("filter:" + session.getId());
                Object username = session.getAttribute("username");
                if(username == null){
                    response.getWriter().println(gson.toJson(new Result(10000,null,"请登录后访问")));
                    return;
                }

            }
            chain.doFilter(httpServletRequest, httpServletResponse);
        }

    }

    private boolean auth(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        if((request.getContextPath() + "/api/admin/admin/login").equals(requestURI)){
            return false;
        }
        return true;
    }
}
